package stark.app.function.step;

import android.Manifest;
import android.util.Log;

import androidx.annotation.NonNull;

import com.blankj.utilcode.constant.TimeConstants;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.stark.stepcounter.lib.StepCounterService;
import com.stark.stepcounter.lib.StepSportInfo;
import com.stark.stepcounter.lib.db.StepDayBean;
import com.stark.stepcounter.lib.db.StepDbManager;

import org.jetbrains.annotations.NotNull;

import java.util.List;

import stark.app.R;
import stark.app.databinding.ActivityStepCounterDemoBinding;
import stark.common.basic.base.BaseNoModelActivity;

/**
 * Author：daizhongbin on 2023/3/10
 * Email：1027154338@qq.com
 * Desc:
 */
public class StepCounterDemoActivity extends BaseNoModelActivity<ActivityStepCounterDemoBinding> implements StepCounterService.IStepChangeListener {
    @Override
    protected int onCreate() {
        return R.layout.activity_step_counter_demo;
    }

    @Override
    protected void initView() {
        mDataBinding.btnGetRec.setOnClickListener(v -> {
            long endTime = System.currentTimeMillis();
            long startTime = endTime - 7 * TimeConstants.DAY;
            List<StepDayBean> dayBeans = StepDbManager.getInstance().stepDayDao().get(startTime, endTime);
            if (dayBeans != null) {
                Log.e("dzb", "dayBeans = " + GsonUtils.toJson(dayBeans));
            }
        });
    }

    @Override
    protected void initData() {
        StepCounterService.addListener(this);
        PermissionUtils.permission(Manifest.permission.ACTIVITY_RECOGNITION)
                .callback(new PermissionUtils.SimpleCallback() {
                    @Override
                    public void onGranted() {
                        StepCounterService.start(StepCounterDemoActivity.this);
                    }

                    @Override
                    public void onDenied() {
                        ToastUtils.showShort("未授予权限");
                    }
                })
                .request();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        StepCounterService.delListener(this);
    }

    @Override
    public void onStepChanged(@NonNull @NotNull StepSportInfo info) {
        StringBuilder builder = new StringBuilder();
        builder.append("今天所走步数为：" + info.stepCount);
        builder.append("\n");
        builder.append("距离为：" + info.distance + " 米");
        builder.append("\n");
        builder.append("消耗卡路里为：" + info.calorie + " 卡");
        builder.append("\n");
        builder.append("耗时为：" + info.duration + " 秒");
        mDataBinding.tvStep.setText(builder.toString());
    }
}
